import json
import time
from datetime import datetime, timezone

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework import viewsets
from rest_framework.decorators import action

from .diseases_recognition import diseases_recognition
from .serializers import *


class RecognitionViewSet(viewsets.ModelViewSet):
    queryset = recognition.objects.all()
    serializer_class = RecognitionSerializer

    @action(methods=['post'], detail=False)
    def recognitionImage(self, request):
        file = request.FILES.get('file')

        try:
            # 构造图片保存路径
            t = int(time.time())
            fname = str(t) + "-" + file.name
            file_path = './media/img/' + fname
            # 保存图片
            with open(file_path, 'wb+') as f:
                f.write(file.read())
                f.close()
            rec_result = diseases_recognition(file_path)
            print(rec_result)
            for index, rec in enumerate(rec_result):
                thisPest = list(pest.objects.values().filter(NameZHCN=rec["NameZHCN"]))[0]
                rec_result[index]["Pid"] = thisPest["Pid"]
                rec_result[index]["Introduction"] = thisPest["Introduction"]
            response = {'filepath': file_path, 'code': 200, 'msg': "识别成功", "rec_result": rec_result, "fname": fname,
                        "time": t}
        except Exception as e:
            print(e)
            response = {'file': '', 'code': 201, 'msg': "识别失败"}

        return JsonResponse(response, safe=False)

    @action(methods=['GET'], detail=False, url_path="/recognition/<uid>")
    @csrf_exempt
    def findRecByUid(self, request, uid):
        thisRec = recognition.objects.values().filter(Uid=uid)
        if (len(thisRec) == 0):
            return JsonResponse({'status': 0, 'message': '识别记录不存在'})
        else:
            return JsonResponse({'status': 1, 'message': '识别记录存在', 'data': list(thisRec)}, safe=False)

    @action(methods=['post'], detail=False)
    def postRecognition(self, request):
        """
        将识别结果写入数据库（适配你的返回数据格式）
        ---
        请求参数示例：
        {
            "filepath": "./media/img/1745460173-1679846607-0.jpg",
            "rec_result": [
                {
                    "NameZHCN": "扁豆斑点病",
                    "Synonyms": "0.55",
                    "Pid": 998,
                    "Introduction": "..."
                },
                ...
            ],
            "time": 1745460173  # Unix 时间戳
            "uid": 123  # 用户ID（可选）
        }
        """
        try:
            # 解析请求数据
            rec_results = request.data.get('rec_result', [])
            filepath = request.data.get('filepath')
            timestamp = request.data.get('time')
            uid = request.data.get('uid', None)  # 用户ID可选

            if not rec_results or not filepath or not timestamp:
                return JsonResponse({
                    "code": 400,
                    "msg": "缺少必要参数"
                }, status=400)

            # 处理时间戳 -> 转换为带时区的 datetime 对象
            try:
                rtime = datetime.fromtimestamp(int(timestamp), tz=timezone.utc)
            except Exception as e:
                return JsonResponse({
                    "code": 400,
                    "msg": f"时间戳解析失败: {str(e)}"
                }, status=400)

            # 序列化 rec_results 为 JSON 字符串
            try:
                result_json = json.dumps(rec_results, ensure_ascii=False)
            except Exception as e:
                return JsonResponse({
                    "code": 400,
                    "msg": f"无法序列化识别结果: {str(e)}"
                }, status=400)

            # 创建数据库记录
            record = recognition(
                Uid=uid,
                Result=result_json,
                Rtime=rtime,
                Rimg=filepath  # 使用完整的文件路径
            )
            record.full_clean()  # 验证模型字段
            record.save()

            return JsonResponse({
                "code": 200,
                "msg": "成功保存记录",
                "record_id": record.Rid
            }, status=201)

        except Exception as e:
            return JsonResponse({
                "code": 500,
                "msg": f"保存失败: {str(e)}"
            }, status=500)